import request from "@/utils/request";
import { genKeyPair } from "@/api/genKeyPair";
// pc端固定客户端授权id
const clientId =
  sessionStorage.getItem("clientid") || import.meta.env.VITE_APP_CLIENT_ID;
const encryptHeader = import.meta.env.VITE_APP_ENCRYPT_HEADER;

// 登录方法
export function login(tenantId, username, password, code, uuid) {
  const params = {
    tenantId,
    username,
    password,
    code,
    uuid,
    clientId: clientId,
    grantType: "password",
  };
  return new Promise((resolve, reject) => {
    genKeyPair((uuid, public_key) => {
      request({
        url: "/auth/back/login",
        headers: {
          isToken: false,
          isEncrypt: true,
          [encryptHeader]: uuid,
          publicKey: public_key,
          repeatSubmit: false,
        },
        method: "post",
        data: params,
      })
        .then((res) => {
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  });
}
// 二维码登录接口获取toke和clientId
export function loginUseCodeAPI(data) {
  return request({
    url: "/auth/login",
    method: "post",
    data: data,
  });
}
// 二维码图片接口
export function getCodeApi(token) {
  return request({
    url: "/auth/downloadScanCode",
    headers: {
      Authorization: `Bearer ${token}`,
    },
    responseType: "arraybuffer",
    method: "get",
  });
}
// 获取UUID
export function getUUIDApi(UUID, token) {
  return request({
    url: "/auth/login?UUID=" + UUID,
    headers: {
      Authorization: `Bearer ${token}`,
    },
    method: "get",
  });
}
// 注册方法
export function register(data) {
  const params = {
    ...data,
    clientId: clientId,
    grantType: "password",
  };
  return new Promise((resolve, reject) => {
    genKeyPair((uuid, public_key) => {
      request({
        url: "/auth/register",
        headers: {
          isToken: false,
          isEncrypt: true,
          [encryptHeader]: uuid,
          publicKey: public_key,
        },
        method: "post",
        data: params,
      })
        .then((res) => {
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  });
}

// 获取用户详细信息
export function getInfo() {
  return request({
    url: "/system/user/getInfo",
    method: "get",
  });
}

// 退出方法
export function logout() {
  return request({
    url: "/auth/logout",
    method: "post",
  });
}

// 获取验证码
export function getCodeImg() {
  return request({
    url: "/auth/code",
    headers: {
      isToken: false,
    },
    method: "get",
    timeout: 20000,
  });
}

// 获取租户列表
export function getTenantList() {
  return request({
    url: "/auth/tenant/list",
    headers: {
      isToken: false,
    },
    method: "get",
  });
}
